

<!doctype html>
<html ng-app="form-example1">
<head>
    <script src="http://code.angularjs.org/1.2.25/angular.min.js"></script>
</head>
<body>
<div>
    <form name="form" class="css-form" novalidate>
        <div>
            大小 (整数 0 - 10):
            <input type="number" ng-model="size" name="size"
                   min="0" max="10" integer /><br />
            <span ng-show="form.size.$error.integer">这是无效的数字!</span>
            <span ng-show="form.size.$error.min || form.size.$error.max">
                值必需在0到10之间!</span>
        </div>

        <div>
            长度 (浮点):
            <input type="text" ng-model="length" name="length" smart-float />
            <br />
            <span ng-show="form.length.$error.float">
                这是无效的浮点数!</span>
        </div>
    </form>
</div>
</body>
<script type="text/javascript">
    var app = angular.module('form-example1', []);

    var INTEGER_REGEXP = /^\-?\d+$/;
    app.directive('integer', function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attrs, ctrl) {
                ctrl.$parsers.unshift(function(viewValue) {
                    if (INTEGER_REGEXP.test(viewValue)) {
                        // 验证通过
                        ctrl.$setValidity('integer', true);
                        return viewValue;
                    } else {
                        // 验证不通过 返回 undefined (不会有模型更新)
                        ctrl.$setValidity('integer', false);
                        return undefined;
                    }
                });
            }
        };
    });

    var FLOAT_REGEXP = /^\-?\d+((\.|\,)\d+)?$/;
    app.directive('smartFloat', function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attrs, ctrl) {
                ctrl.$parsers.unshift(function(viewValue) {
                    if (FLOAT_REGEXP.test(viewValue)) {
                        ctrl.$setValidity('float', true);
                        return parseFloat(viewValue.replace(',', '.'));
                    } else {
                        ctrl.$setValidity('float', false);
                        return undefined;
                    }
                });
            }
        };
    });
</script>
</html>

